/******************************************************************************
 * @File name   :      MenuBuilderController.java
 *
 * @Author      :      Eric Zhang
 *
 * @Date        :      2011-4-7
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * 2011-4-7 下午02:23:40        Eric Zhang     1.0            Initial Version
 * 2011-10-9 下午05:48:46 HeHao       1.1             Change Method buildMenu
 * 2011-10-19 上午2:27:12 Wu Jianxi            1.2             add current user and user group to model
 * 2011-11-30 上午08:38:48      caijunyi        1.3            fix shortcut menu bug
 *****************************************************************************/
package com.cap.bts.framework.workbench.menu.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.cap.bts.framework.workbench.constant.WorkbenchConstant;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.cap.bts.framework.codemapping.domain.CodeInfo;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.constant.CodeMappingType;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.util.Utils;
import com.cap.bts.framework.menu.constant.MenuTypeConstants;
import com.cap.bts.framework.menu.domain.Menu;
import com.cap.bts.framework.menu.dto.MenuItemDto;
import com.cap.bts.framework.menu.service.IMenuService;
import com.cap.bts.framework.usermgnt.domain.User;
import com.cap.bts.framework.usermgnt.domain.UserGroup;
import com.cap.bts.framework.usermgnt.service.IUserMgntService;

/**
 *
 */
@Controller
public class MenuBuilderController {

    @Autowired
    private IMenuService menuService;
    
    @Autowired
    private ICodeMapping codeMappingService;
    
    @Autowired
    private IUserMgntService userMgntService;
    
    @RequestMapping(value = "/buildMenu")
    public ModelAndView buildMenu(HttpServletRequest req) throws AppException{
        String homePage = "#";
        User currUser = (User) req.getSession().getAttribute("userSession");
        List<MenuItemDto> userMenus = menuService.getDisplayMenus(currUser.getUserCode(),MenuTypeConstants.DEALER);
        
        /*List<Menu> menus;
        try {
            menus = menuService.getGrantedMenusByUserCode(currUser.getUserCode());
        } catch (AppException e) {
            e.printStackTrace();
            return new ModelAndView(WorkbenchConstant.INEX_PAGE);
        }
        if (menus == null) {
            return new ModelAndView(WorkbenchConstant.INEX_PAGE);
        }
        Map<String, MenuItemDto> displayMenus = new HashMap<String, MenuItemDto>();
        MenuItemDto rootDto = new MenuItemDto();
        rootDto.setMenuCode("root");
        displayMenus.put("root", rootDto);
        
        for (Menu menu: menus) {
            MenuItemDto currentMenuDto = null;
            //First to check if current menu is already in the Map or not
            if (displayMenus.containsKey(menu.getMenuCode())) { //update node in the map
                currentMenuDto = displayMenus.get(menu.getMenuCode());
                currentMenuDto.setMenuName(menu.getMenuName()); //update name
            } else { //Create a new current menu node and put in map
                currentMenuDto = new MenuItemDto();
                currentMenuDto.setMenuCode(menu.getMenuCode());
                currentMenuDto.setMenuName(menu.getMenuName());
            }
            displayMenus.put(menu.getMenuCode(), currentMenuDto);
            String parentCode = menu.getParentMenuCode();
            //Check if current menu is first level menu node
            if (!StringUtils.isEmpty(parentCode)) { //if not a first level menu
              //check if Parent node in Map already?
                if (displayMenus.containsKey(parentCode)) { //Add current to parent directly
                    MenuItemDto parentMenuDto = displayMenus.get(parentCode); 
                    currentMenuDto.setParentMenu(parentMenuDto);
                    parentMenuDto.addSubMenus(currentMenuDto);
                } else { //Create an empty parent node and add current to parent
                    MenuItemDto parentMenuDto = new MenuItemDto();
                    parentMenuDto.setMenuCode(parentCode);
                    displayMenus.put(parentCode, parentMenuDto);
                                         
                    parentMenuDto.addSubMenus(currentMenuDto);
                   
                    currentMenuDto.setParentMenu(parentMenuDto);
                }    
            } else { //first level menu, directly add to root
                currentMenuDto.setParentMenu(rootDto);
                rootDto.addSubMenus(currentMenuDto);
            }
        }
        List<MenuItemDto> mainMenuList = (displayMenus.get("root")).getSubMenus();*/
        
        List<Menu> shortcutMenu = menuService.getUserShortcutMenusByUserId(currUser.getId());
        for (Menu menu : shortcutMenu) {
            
            String parentMenuCode = menu.getParentMenuCode();
            if(Utils.notEmpty(parentMenuCode)){
                Menu parentMenu = menuService.getMenuByMenuCode(parentMenuCode);
                if(parentMenu != null){
                    menu.setParentMenuName(parentMenu.getMenuName());
                }
            }
            
            if(null != menu.getBaseUrlType()){
                String site = menuService.getAbsoluteUrlWithMenu(menu);
                menu.setUrl(site+"/"+menu.getUrl());
            }
        }
//        int size = shortcutMenu.size();
//        if(size<6){
//            for(int i=size;i<6;i++){
//                Menu menu = new Menu();
//                menu.setUrl("");
//                menu.setPhoneUrl("logo/tag_peixun.jpg");
//                menu.setMenuName(CodeTextUtils.getText("auto", 1));
//                shortcutMenu.add(menu);
//                size++;
//            }
//        }
        if(userMenus != null && !userMenus.isEmpty()){
            List<MenuItemDto> list = userMenus.get(0).getSubMenus();
            if(list != null && !list.isEmpty()){
                homePage = list.get(0).getMenuUrl();
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("menuItems", userMenus);
        map.put("homePage", homePage);
        map.put("shortcutMenu", shortcutMenu);
        
//        List<CodeInfo> listMaxDay = codeMappingService.getCodeInfoByType(CodeMappingType.MAX_PASSWORD_VALID_DAYS.getValue());
//        List<CodeInfo> listTipDay = codeMappingService.getCodeInfoByType(CodeMappingType.REMINDER_DAYS_BEFORE_PWD_EXPIRED.getValue());
        int maxDay = 0;
        int tipDay = 0;
//        if(listMaxDay!=null && listMaxDay.size()>0){
//            maxDay=Integer.parseInt(listMaxDay.get(0).getValue());
//        }
//        if(listTipDay!=null && listTipDay.size()>0){
//            tipDay=Integer.parseInt(listTipDay.get(0).getValue());
//        }
        int notUpdPwdDays = getDays(new Date(), currUser.getLastPwdChangeTime());
//        if((maxDay-tipDay)<=notUpdPwdDays){//密码即将过期提醒
//            map.put("AboutToExpired", maxDay - notUpdPwdDays);
//        }
        
        if(currUser.getLastLoginTime() == null){
            map.put("isFirstLogin", true);
        }
        
        currUser.setLastLoginTime(new Date());
        map.put("currentUser", currUser);
        
        //get default user group
        UserGroup userGroup = userMgntService.getDefaultUserGroupByUserId(currUser.getId());
        if(null == userGroup){
            userGroup = new UserGroup();
        }
        map.put("currentUserGroup", userGroup);
        
        
        
        return new ModelAndView(WorkbenchConstant.INEX_PAGE, map);
    }
    
    private int getDays(Date startDate,Date endDate){
        if(endDate==null){
            endDate = new Date();
        }
        Long start = startDate.getTime();
        Long end  = endDate.getTime();
        Long quot = start-end; 
        return (int) (quot/(1000*60*60*24));
    }
}
